﻿using System;
using System.Web;

namespace WebForms.Account
{
    public partial class Logout : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var idToken = HttpContext.Current.Session["IdToken"]?.ToString();// 从本地存储获取id_token
            // 清除本地存储的令牌
            HttpContext.Current.Session.Remove("AccessToken");
            HttpContext.Current.Session.Clear();
            DelCookeis();

            HttpContext.Current.GetOwinContext().Authentication.SignOut("Cookies");
            //HttpContext.Current.GetOwinContext().Authentication.SignOut("oidc");

            // 重定向到IdentityServer的登出页面
            string endSessionUrl = "https://localhost:5001/connect/endsession";
            string postLogoutRedirectUri = "http://localhost:43389/about.aspx";
            
            string url = $"{endSessionUrl}?post_logout_redirect_uri={HttpUtility.UrlEncode(postLogoutRedirectUri)}&id_token_hint={HttpUtility.UrlEncode(idToken)}";
            Response.Redirect(url);
        }

        #region 删除cookies
        ///<summary>
        /// 删除cookies
        ///</summary>
        public void DelCookeis()
        {
            foreach (string cookiename in Request.Cookies.AllKeys)
            {
                var cookies = Request.Cookies[cookiename];
                if (cookies != null)
                {
                    cookies.Expires = DateTime.Today.AddDays(-1);
                    Response.Cookies.Add(cookies);
                    Request.Cookies.Remove(cookiename);
                }
            }
        }
        #endregion
    }
}